package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public List<ProductModel> findAll() {
        String sql = "SELECT p.*,c.name cuisineName FROM product  p,cuisine c" +
                " where p.cuisine_id =c.id";
        ResultSet resultSet = JDBC.findAll(sql);
        return setList(resultSet);
    }

    @Override
    public int add(ProductModel productModel) {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        Date date = new Date();
        String sql = "insert into product " +
                "(name,normal_price,price," +
                "content,is_show,is_recommend," +
                "img_href,cuisine_id," +
                "create_time,update_time) " +
                "values('" + productModel.getName() + "'," +
                "" + productModel.getNormalPrice() + "," +
                "" + productModel.getMarketPrice() + "," +
                "'" + productModel.getContent() + "'," +
                "" + productModel.getShow() + "," +
                "" + productModel.getRecomend() + "," +
                "'" + productModel.getImgHref() + "'," +
                "" + productModel.getCuisineId() + "," +
                "now()," +
                "now())";
        return JDBC.update(sql);
    }


    private List<ProductModel> setList(ResultSet resultSet) {
        List<ProductModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                ProductModel productModel = new ProductModel();
                productModel.setId(resultSet.getInt("id"));
                productModel.setName(resultSet.getString("name"));
                productModel.setMarketPrice(resultSet.getFloat("normal_price"));
                productModel.setNormalPrice(resultSet.getDouble("price"));
                productModel.setContent(resultSet.getString("content"));
                productModel.setShow(resultSet.getBoolean("is_show"));
                productModel.setRecomend(resultSet.getBoolean("is_recommend"));
                productModel.setImgHref(resultSet.getString("img_href"));
                productModel.setCuisineId(resultSet.getInt("cuisine_id"));
                productModel.setCuisineName(resultSet.getString("create_time"));
                productModel.setUpdateTime(resultSet.getString("update_time"));
                productModel.setRemark(resultSet.getString("remark"));
                productModel.setCuisineName(resultSet.getString("cuisineName"));
                list.add(productModel);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
